<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>自定义指令</title>
    <script type="text/javascript" src="./../vue.js/vue.js"></script>
  </head>

  <body>
    <!-- 
			需求: 定义一个 v-focus指令, 和v-bind功能类似, 但可以让其所绑定的input元素默认获取焦点.
		-->

    <div id="root">
      <h2>当前的n值是: <span v-text="n"></span></h2>
      <button @click="n++">点我n+1</button>
      <input type="text" v-focus="n" />
    </div>

    <script type="text/javascript">
      Vue.config.productionTip = false;

      new Vue({
        el: "#root",
        data: {
          n: 1,
        },
        directives: {
          focus: {
            // 指令与元素成功绑定时(一上来)
            bind(element, binding) {
              element.value = binding.value;
            },
            // 指令所在元素被插入页面时
            inserted(element, binding) {
              element.focus();
            },
            // 指令所在的模板被重新解析时
            update(element, binding) {
              element.value = binding.value;
            },
          },
        },
      });
    </script>
  </body>
</html>
